package com.heima.search.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dto.UserSearchDto;
import com.heima.model.search.pojo.SearchHistory;
import com.heima.search.service.SearchService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1")
public class SearchController {
    @Autowired
    private SearchService searchService;

    /**
     * 文章搜索
     * @param dto
     * @return
     * @throws IOException
     */
    @PostMapping(path = "/article/search/search")
    @ApiOperation("文章搜索")
    public ResponseResult search(@RequestBody UserSearchDto dto) throws IOException {
        List<Map<String, Object>> list =  searchService.search(dto);
        return ResponseResult.success(list);
    }

    /**
     * 历史搜索展示
     * @param dto
     * @return
     * @throws IOException
     */
    @PostMapping(path = "/history/load")
    @ApiOperation("历史搜索展示")
    public ResponseResult searchHistory(@RequestBody UserSearchDto dto) throws IOException {
        List<SearchHistory> searchHistories = searchService.searchHistory(dto);
        return ResponseResult.success(searchHistories);
    }

    /**
     * 历史删除
     * @param dto
     * @return
     * @throws IOException
     */
    @PostMapping(path = "/history/del")
    @ApiOperation("历史删除")
    public ResponseResult deleteHistory(@RequestBody SearchHistory dto){
        if (ObjectUtil.isEmpty(dto.getId())){
            return ResponseResult.error(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        searchService.removeById(dto.getId());
        return ResponseResult.success();
    }

    /**
     * 搜索自动补全
     * @param dto
     * @return
     * @throws IOException
     */
    @PostMapping(path = "/associate/search")
    @ApiOperation("搜索自动补全")
    public ResponseResult autoCompletion(@RequestBody UserSearchDto dto) throws IOException {
        //1、空过滤，没有任何关键词，不需要做自动补全搜索
        if (StrUtil.isEmpty(dto.getSearchWords())){
            return ResponseResult.success(new ArrayList<>());
        }
        List<String> searchHistories = searchService.autoCompletion(dto);

        return ResponseResult.success(searchHistories);
    }
}
